package com.shqcjd.yunweiyanoperator.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.app.AppConstant;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.CompanyRegisterSuccessEvebt;
import com.shqcjd.yunweiyanoperator.model.pojo.CompanyRegisterBean;
import com.shqcjd.yunweiyanoperator.model.pojo.LoginBean;
import com.shqcjd.yunweiyanoperator.model.pojo.RegisterCompanyBean;
import com.shqcjd.yunweiyanoperator.model.pojo.FileBean;
import com.shqcjd.yunweiyanoperator.ui.activity.staff.MainActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.AlbumUtils;
import com.shqcjd.yunweiyanoperator.util.AppManager;
import com.shqcjd.yunweiyanoperator.util.MyGlideEngine;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.widget.LoginTipsDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LicenseUpActivity extends BaseActivity {

    @BindView(R.id.btn_finish)
    ImageView btnLicenseFinish;
    @BindView(R.id.iv_license_upload)
    ImageView ivLicenseUpload;
    @BindView(R.id.tv_license_commit)
    TextView tvLicenseCommit;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    RegisterCompanyBean mBean;

    private final int IMAGE_FILE_RESULT_CODE = 10111;
    private Context mContext;
    private String albumStringPath;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_license_up;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
        mBean = (RegisterCompanyBean) getIntent().getSerializableExtra("mBean");
    }

    @Override
    public void initView() {
        super.initView();
        tvTitle.setText("拍摄/上传营业执照");
    }

    public void requestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(LicenseUpActivity.this)
                                    .choose(MimeType.ofImage()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(1) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    private void companyRegisterHttp() {
        Map<String, String> map = new HashMap<>();
        map.put("businessName", mBean.businessName);
        map.put("telNumber", mBean.telNumber);
        map.put("businessLicenseUrl", mBean.businessLicenseUrl);
        map.put("mainBusiness", mBean.mainBusiness);
//        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        String json =  new JSONObject(map).toString();
        ApiService.businessRegister(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<CompanyRegisterBean>>() {

                    @Override
                    public void _onNext(ResponseData<CompanyRegisterBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "公司注册成功");
                            CompanyRegisterSuccessEvebt cBean = new CompanyRegisterSuccessEvebt();
                            cBean.name = retData.data.businessName;
                            cBean.companyId = retData.data.businessId+"";
                            EventBus.getDefault().post(cBean);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        uploadFile(new File(albumStringPath));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    private void login() {
        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", mBean.phoneNumber);
        map.put("password", mBean.password);
        //        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        ApiService.login(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        if (retData.retCode == 10000) {
                            PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, retData.data.phoneNumber);
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setString(mContext, PrefUtils.TOKEN, retData.data.token);
                            PrefUtils.setBoolean(mContext, PrefUtils.FIRST_LOGIN, true);
                            PrefUtils.setInt(mContext, PrefUtils.USER_ID, retData.data.id);
                            PrefUtils.setInt(mContext, PrefUtils.USER_GUIDE_ID, Integer.parseInt("1"+retData.data.id));//用于远程指导和信令的用户id 操作端前缀加1 专家端前缀加2
                            PrefUtils.setString(mContext, PrefUtils.USER_ACCOUNT, mBean.phoneNumber);
                            PrefUtils.setString(mContext, PrefUtils.USER_PWD, mBean.password);
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.userType);
                            PrefUtils.setInt(mContext, PrefUtils.USER_STATE, retData.data.status);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.userName);
                            PrefUtils.setString(mContext, PrefUtils.BUSINESSId, retData.data.businessId);
                            PrefUtils.setString(mContext, PrefUtils.APPCODE, retData.data.appCode);
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    if (retData.data.userType == 1) {
                                        //管理员用户界面
                                        startActivity(new Intent(mContext, AdministerMainActivity.class));
                                    } else if (retData.data.userType == 2) {
                                        //普通员工界面
                                        startActivity(new Intent(mContext, MainActivity.class));
                                    }
                                    AppManager.getAppManager().finishAllActivity();
                                }
                            });
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, "登录失败");
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void uploadFile(File files) {
        ApiService.uploadLicense(files)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<FileBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("上传文件中");
                    }

                    @Override
                    public void _onNext(ResponseData<FileBean> retData) {
                        if (retData.retCode == 10000) {
                            mBean.businessLicenseUrl = retData.data.url;
//                            Glide.with(mContext).load(mBean.businessLicenseUrl).into(ivLicenseUpload);
                            ivLicenseUpload.setBackgroundResource(R.color.transparent);
                            Glide.with(mContext).load(albumStringPath).into(ivLicenseUpload);
                            ToastUtils.showShort(mContext, "上传成功");
                        } else {
                            ToastUtils.showShort(mContext, "上传失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @OnClick({R.id.btn_finish, R.id.iv_license_upload, R.id.tv_license_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.iv_license_upload:
                requestLocationAndCallPermission();
                break;
            case R.id.tv_license_commit:
                if(!mBean.businessLicenseUrl.equals("")){
                    companyRegisterHttp();
                }else{
                    ToastUtils.showShort(mContext, "请先上传营业执照");
                }

                finish();
                break;
        }
    }
}
